//
//  CLLNetWorkManager+Extension.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/11.
//  Copyright © 2017年 DDC. All rights reserved.
//

import Foundation

// MARK: - 封装该程序的数据请求方法
extension CLLNetWorkManager {
    
    func statusList(sinceId:Int64 = 0,maxId:Int64 = 0, completion:@escaping (_ list:[[String:Any]]?,_ isSuccess:Bool)->()){
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["since_id":"\(sinceId)",
            "max_id":"\(maxId > 0 ? maxId - 1 : 0)"]
        // 封装token的方法
        tokenRequest(urlString: urlString, params: params) { (json, isSuccess) in
            
            guard let result = json as? NSDictionary,
                let resultDict = result["statuses"] as? [[String:Any]] else {
                    return
            }
            
            completion(resultDict, isSuccess)
            
        }
    }
    
}
// MARK: - OAuth相关方法
extension CLLNetWorkManager {
    /// 获取授权的accesstoken--获取授权
    ///
    /// - Parameters:
    ///   - code: 授权获得的code
    ///   - completion: 回调信息--自己需要什么就回调什么
    func loadAccessToken(code:String,completion:@escaping (_ isSuccess:Bool)->()) {
        
        // urlstring
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id":CLLWBAppKey,
                      "client_secret":CLLWBAppSecret,
                      "grant_type":"authorization_code",
                      "code":code,
                      "redirect_uri":CLLWBRedirectURI]
        request(method: .POST, urlString: urlString, params: params) { (json, isSuccess) in
            
            // 字典转模型
            self.userAccount.yy_modelSet(with: (json as? [String:Any]) ?? [:])
            
            // 加载用户信息
            self.loadUserInfo(completion: { (dict) in
                print(dict)
                self.userAccount.yy_modelSet(with: dict)
                // 将用户头像用户名 保存到沙盒中
                self.userAccount.saveAccount()

                // 完成回调
                completion(isSuccess)
            })
        }
        
    }
}

// MARK: - 获取用户信息
extension CLLNetWorkManager {
    func loadUserInfo (completion:@escaping (_ dict:[String:Any])->()) {
        
        guard let uid = userAccount.uid else {
            return
        }
        let urlString = "https://api.weibo.com/2/users/show.json"
        let params = ["uid":uid]
        
        tokenRequest(urlString: urlString, params: params) { (json, isSuccess) in
            completion((json as? [String:Any]) ?? [:])
        }
        
    }
}
